package com.lmscn.lms.api.controller;

import com.google.gson.Gson;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.lmscn.lms.api.model.*;
import com.lmscn.lms.api.util.JsonKit;
import com.lmscn.lms.domain.exam.ExamResultVo;

import net.sf.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Czl on 2015/8/11.
 */
public class SubmitAnswerController extends Controller {

    /**
          * 提交答案
     */
    @Before(Tx.class)
    public void submitSingleAnswer() {
        Long studentId = getParaToLong("studentId");
        Long questionId = getParaToLong("questionId");
        Long testpaperId = getParaToLong("testpaperId");
        String clientAnswer = getPara("myAnswer");
        Map<String, Object> dataMap = new HashMap<String, Object>();
        Testpaper testpaper = Testpaper.dao.findById(testpaperId);   // 试卷
        Question question = Question.dao.findById(questionId);       // 试题
        
        TestpaperItem testpaperItem = TestpaperItem.dao.findByItemIdAndQuestionId(testpaperId, questionId);
        TestpaperResult testpaperResult = TestpaperResult.dao.getByStuIdAndTestpaperId(studentId, testpaperId);
        
        int getScore;   // 获得分数
        int status = 0; // 状态
        if (testpaper.getStr("target_type").equals("courseexam")) {
            Exam courseExam = Exam.dao.findById(testpaper.getLong("target_id"));
            CourseBase courseBase = CourseBase.dao.findById(courseExam.getLong("target_id"));
            CourseStudent courseStudent = CourseStudent.dao.findByCourseIdAndStudentId(courseBase.getLong("id"), studentId);
            // 获取答题分值
            getScore = getExamScore(question, courseExam, clientAnswer);
            // 题目分值
            int score = getExamScore(question, courseExam);
            if (getScore > 0) { // 答对题
                status = 1;
            }
            // 保存选项答案 分数
            updateScore(testpaperItem, testpaper, testpaperResult, studentId, questionId, status, score, clientAnswer);
            // 更新选课表分数
            courseStudent.set("score", testpaperResult.getInt("score"));
            courseStudent.update();
        } else if (testpaper.getStr("target_type").equals("coursetest")) {
            Test courseTest = Test.dao.findById(testpaper.getLong("target_id"));

            getScore = getTestScore(question, courseTest, clientAnswer);
            // 题目分值
            int score = getTestScore(question, courseTest);
            if (getScore > 0) { // 答对题
                status = 1;
            }
            // 保存选项答案 分数
            updateScore(testpaperItem, testpaper, testpaperResult, studentId, questionId, status, score, clientAnswer);

        } else if (testpaper.getStr("target_type").equals("faceclazzexam")) {
            Exam clazzExam = Exam.dao.findById(testpaper.getLong("target_id"));
            Clazz clazz = Clazz.dao.findById(clazzExam.getLong("target_id"));
            ClazzStudent clazzStudent = ClazzStudent.dao.findByClazzIdAndStuId(studentId, clazz.getLong("id"));
            // 获取答题分值
            getScore = getExamScore(question, clazzExam, clientAnswer);
            // 题目分值
            int score = getExamScore(question, clazzExam);
            if (getScore > 0) { // 答对题
                status = 1;
            }
            // 保存选项答案 分数
            updateScore(testpaperItem, testpaper, testpaperResult, studentId, questionId, status, score, clientAnswer);
            // 更新选课表分数
            clazzStudent.set("class_exam_score", testpaperResult.getInt("score"));
            clazzStudent.update();

        } else if (testpaper.getStr("target_type").equals("faceclazztest")) {
            Test clazzTest = Test.dao.findById(testpaper.getLong("target_id"));
            // 获取答题分值
            getScore = getTestScore(question, clazzTest, clientAnswer);
            // 题目分值
            int score = getTestScore(question, clazzTest);
            if (getScore > 0) { // 答对题
                status = 1;
            }
            // 保存选项答案 分数
            updateScore(testpaperItem, testpaper, testpaperResult, studentId, questionId, status, score, clientAnswer);

        } else if (testpaper.getStr("target_type").equals("myexam")) {
            Exam exam = Exam.dao.findById(testpaper.getLong("target_id"));
            MyExam myExam = MyExam.dao.findById(exam.getLong("target_id"));
            MyExamStudent myExamStudent = MyExamStudent.dao.findScore(myExam.getLong("student_id"), myExam.getLong("id"));
            // 获取答题分值
            getScore = getExamScore(question, exam, clientAnswer);
            // 题目分值
            int score = getExamScore(question, exam);
            if (getScore > 0) { // 答对题
                status = 1;
            }
            // 保存选项答案 分数
            updateScore(testpaperItem, testpaper, testpaperResult, studentId, questionId, status, score, clientAnswer);
            // 更新学员考试表成绩
            myExamStudent.set("myexam_score", testpaperResult.getInt("sc  ore"));
            myExamStudent.update();
        } else if (testpaper.getStr("target_type").equals("myexamtest")) {
            Test myexamTest = Test.dao.findById(testpaper.getLong("target_id"));
            // 获取答题分值
            getScore = getTestScore(question, myexamTest, clientAnswer);
            // 题目分值
            int score = getTestScore(question, myexamTest);
            if (getScore > 0) { // 答对题
                status = 1;
            }
            // 保存选项答案 分数
            updateScore(testpaperItem, testpaper, testpaperResult, studentId, questionId, status, score, clientAnswer);
        }
        dataMap.put("totalScore", testpaperResult.getInt("score"));
        renderJson(JsonKit.mapToJson(dataMap, 39));
    }

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
//	public List<Question> getAllQuestionsByTestpaperId(String questionIds){
//		List<Question> questionList = new ArrayList<Question>();
//		questionList.addAll(this.questionManager.getQuestionList(questionIds));
//		questionList.addAll(this.questionManager.getQuestionList(testpaper.getMultiQuestions()));
//		questionList.addAll(this.questionManager.getQuestionList(testpaper.getDetermineQuestions()));
//		questionList.addAll(this.questionManager.getQuestionList(testpaper.getFillBlankQuestions()));
//		return questionList;
//	}
//    
//	public Map<Question, String> getAnswersFromRequest(String answers, Testpaper testpaper) {
//		Map<Question,String> map = new HashMap<Question,String>();
//		if (answers==null || "".equals(answers) || testpaper==null) {
//			return map;
//		}
//		
//		String determineIds = testpaper.getStr("determine_questions");  // 判断题
//		String fillIds = testpaper.getStr("fill_blank_questions");  // 填空
//		String singleIds = testpaper.getStr("single_questions");
//		String multiIds = testpaper.getStr("multi_questions");
//		JSONObject answerJson = JSONObject.fromObject(answers);
//		
//		
//		
//		for (int i = 0; i <questionList.size(); i++) {
//			Question question = questionList.get(i);
//			String answer = "";
//			String[] ss = request.getParameterValues(
//					"answer" + question.getId());
//			if (!empty(ss)) {
//				for (int j = 0; j < ss.length; j++) {
//					answer += ss[j];
//				}
//			}
//			map.put(question, answer);
//		}
//		return map;
//	}
    
    /**
     * 最终交卷
     */
	public void submitPaper() {
		Long testpaperResultId = getParaToLong("testpaperResultId");
		Long studentId = getParaToLong("studentId");
		String userType = getPara("userType");
		String userAnswer = getPara("answer");
		
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Student student = Student.dao.findById(studentId);
		String studyGroup = student.getStr("study_group");
		if (!userType.equals(studyGroup)) {
			dataMap.put("error_code", "1");
			dataMap.put("msg", "用户登录类型不匹配!");
			renderJson(JsonKit.mapToJson(dataMap, 30));
			return ;
		}
		
		TestpaperResult testpaperResult = TestpaperResult.dao.findById(testpaperResultId);
		Long testpaperId = testpaperResult.getLong("testpaper_id");
		Testpaper testpaper = Testpaper.dao.findById(testpaperId);  // 试卷
//		JSONObject answerJson = JSONObject.fromObject(userAnswer);  // answer: {qid:answer,...}
		Gson gson = new Gson();
		Map<String, String> resultMap = new HashMap<String, String>();
		resultMap = gson.fromJson(userAnswer, resultMap.getClass());
		
		saveResult(testpaperResult, testpaper, resultMap, "finished");
//		Long examId = testpaperResult.getLong("target_id");
//		Exam exam = Exam.dao.findById(examId);  // 获取考试信息
		
		dataMap.put("error_code", 0);
		dataMap.put("msg", "success");
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("score", testpaperResult.getInt("score"));
		data.put("usedTime", testpaperResult.getInt("used_time"));
		dataMap.put("data", data);
		renderJson(JsonKit.mapToJson(dataMap, 30));
    }
	
	
	public boolean saveResult(TestpaperResult testpaperResult, Testpaper testpaper,
			Map<String, String> answerMap, String paperStatus) {
		//保存新的答题结果
		StringBuffer sb = new StringBuffer();
		
		ExamResultVo determine_vo = processPaperResult(answerMap,
				testpaper.getStr("determine_questions"),
				testpaper.getInt("single_question_score"));    // 判断题
		ExamResultVo fill_vo = processPaperResult(answerMap,
				testpaper.getStr("fill_blank_questions"),
				testpaper.getInt("single_question_score"));   // 填空
		ExamResultVo single_vo = processPaperResult(answerMap,
				testpaper.getStr("single_questions"),
				testpaper.getInt("single_question_score"));
		ExamResultVo multi_vo = processPaperResult(answerMap,
				testpaper.getStr("multi_questions"),
				testpaper.getInt("single_question_score"));
		
		int paperScore = determine_vo.getScore() + fill_vo.getScore() + single_vo.getScore() + multi_vo.getScore();
		int rightCount = determine_vo.getRight() + fill_vo.getRight() + single_vo.getRight() + multi_vo.getRight();
		
		Date now = new Date();
		testpaperResult.set("single_answers", single_vo.getAnswer());
		testpaperResult.set("multi_answers", multi_vo.getAnswer());
		testpaperResult.set("determine_answers", determine_vo.getAnswer());
		testpaperResult.set("fill_blank_answers", fill_vo.getAnswer());
		testpaperResult.set("single_right_count", single_vo.getRight());
		testpaperResult.set("multi_right_count", multi_vo.getRight());
		testpaperResult.set("determine_right_count", determine_vo.getRight());
		testpaperResult.set("fill_blank_right_count", fill_vo.getRight());
		testpaperResult.set("single_score", single_vo.getScore());
		testpaperResult.set("multi_score", multi_vo.getScore());
		testpaperResult.set("determine_score", determine_vo.getScore());
		testpaperResult.set("fill_blank_score", fill_vo.getScore());
		testpaperResult.set("credit", 0);
		testpaperResult.set("status", paperStatus);
		testpaperResult.set("score", paperScore);
		testpaperResult.set("end_time", now);
		testpaperResult.set("right_count", rightCount);
		
		// 非连续计时，并且是保存草稿
		if (!testpaperResult.getBoolean("is_count_durative") && !"finished".equals(paperStatus)) {
			long da = now.getTime();    // 当前时间
			long db = testpaperResult.getTimestamp("last_save_time").getTime();  //上次计时时间
			int usedDraftTime = (int)((da - db) / 1000);
			testpaperResult.set("left_seconds", testpaperResult.getInt("left_seconds") - usedDraftTime);  // 剩余计时时间
		}
		long a = testpaperResult.getDate("end_time").getTime();
		long b = testpaperResult.getDate("begin_time").getTime();
		int c = (int)((a - b) / 1000);
		testpaperResult.set("used_time", c);
		testpaperResult.set("last_save_time", now);
		
		return testpaperResult.update();
	}
	
	
	public ExamResultVo processPaperResult(Map<String, String> answerMap, String questionIds, int score) {
		StringBuffer userAnswer = new StringBuffer();
		ExamResultVo vo = new ExamResultVo();
		int total_score = 0;
		int right_num = 0;
		
		if (questionIds!=null && !"".equals(questionIds)) {
			String[] ids = questionIds.split(",");
			if (ids!=null && ids.length>0) {
				for (int i=0; i<ids.length; i++) {
					Question question = Question.dao.findById(ids[i]);
					if (!answerMap.containsKey(ids[i])) {
						userAnswer.append(",");
						continue;
					}
					String uAnswer = answerMap.get(ids[i]);
					String qAnswer = question.getStr("answer");
					if (uAnswer.trim().toUpperCase().equals(qAnswer)) {
						total_score += score;
						userAnswer.append(uAnswer);
						right_num ++;
					}
					userAnswer.append(",");
				}
				String answers = userAnswer.toString();
				answers = answers.endsWith(",") ? answers.substring(0, answers.length()-1) : answers;
				vo.setAnswer(answers);
				vo.setRight(right_num);
				vo.setScore(total_score);
			}
		}
		
		return vo;
	}
	
	
	/**
	 * 如果字符串以逗号结尾，删除字符串的最后一个逗号
	 * @param str
	 * @return
	 */
	private String removeLastComma(String str){
		if(str == null){
			return str;
		}
		if(str.endsWith(",")){
			return str.substring(0, str.length()-1);
		}
		return str;
	}
    
    
    
    
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

    /**
     * 保存，暂停等
     */
    public void savePaper() {

        Long studentId = getParaToLong("studentId");
        Long testpaperId = getParaToLong("testpaperId");
        int usedTime = getParaToInt("usedTime");
        Map<String, Object> dataMap = new HashMap<String, Object>();
        // 查询试卷
        TestpaperResult testpaperResult = TestpaperResult.dao.getByStuIdAndTestpaperId(studentId, testpaperId);

        int beforeUsed = testpaperResult.getInt("used_time");
        int totalTime = usedTime + beforeUsed;
        testpaperResult.set("used_time", totalTime);
        testpaperResult.set("status", "paused");
        testpaperResult.set("update_time", new Date());//保存时间
        testpaperResult.set("used_time", usedTime);
        testpaperResult.update();
        dataMap.put("error_code", 0);
        dataMap.put("msg", "success");
        renderJson(JsonKit.mapToJson(dataMap, 30));
    }

    /**
     * 获取取得分数
     *
     * @param question
     * @param exam
     * @param myAnswer
     * @return
     */
    private int getExamScore(Question question, Exam exam, String myAnswer) {
        int questionScore = 0;
        int getScore = 0;
        // 获取题目分值
        if (question.getStr("type").equals("single_choice")) { // 单选
            questionScore = exam.getInt("rand_single_score");
        } else if (question.getStr("type").equals("multi_choice")) { // 多选
            questionScore = exam.getInt("rand_multi_score");
        } else if (question.getStr("type").equals("determine_choose")) { //判断
            questionScore = exam.getInt("rand_choose_score");
        } else if (question.getStr("type").equals("fill_choice")) { // 填空
            questionScore = exam.getInt("rand_fill_score");
        }
        if (question.getStr("answer").equals(myAnswer)) { // 答对题
            getScore = questionScore;
        }
        return getScore;
    }

    private int getExamScore(Question question, Exam exam) {
        int questionScore = 0;
        // 获取题目分值
        if (question.getStr("type").equals("single_choice")) { // 单选
            questionScore = exam.getInt("rand_single_score");
        } else if (question.getStr("type").equals("multi_choice")) { // 多选
            questionScore = exam.getInt("rand_multi_score");
        } else if (question.getStr("type").equals("determine_choose")) { //判断
            questionScore = exam.getInt("rand_choose_score");
        } else if (question.getStr("type").equals("fill_choice")) { // 填空
            questionScore = exam.getInt("rand_fill_score");
        }
        return questionScore;
    }

    /**
     * 获取取得分数
     *
     * @param question
     * @param test
     * @param myAnswer
     * @return
     */
    private int getTestScore(Question question, Test test, String myAnswer) {
        int questionScore = 0;
        int getScore = 0;
        // 获取题目分值
        if (question.getStr("type").equals("single_choice")) { // 单选
            questionScore = test.getInt("rand_single_score");
        } else if (question.getStr("type").equals("multi_choice")) { // 多选
            questionScore = test.getInt("rand_multi_score");
        } else if (question.getStr("type").equals("determine_choose")) { //判断
            questionScore = test.getInt("rand_choose_score");
        } else if (question.getStr("type").equals("fill_choice")) { // 填空
            questionScore = test.getInt("rand_fill_score");
        }
        if (question.getStr("answer").equals(myAnswer)) { // 答对题
            getScore = questionScore;
        }
        return getScore;
    }

    private int getTestScore(Question question, Test test) {
        int questionScore = 0;
        // 获取题目分值
        if (question.getStr("type").equals("single_choice")) { // 单选
            questionScore = test.getInt("rand_single_score");
        } else if (question.getStr("type").equals("multi_choice")) { // 多选
            questionScore = test.getInt("rand_multi_score");
        } else if (question.getStr("type").equals("determine_choose")) { //判断
            questionScore = test.getInt("rand_choose_score");
        } else if (question.getStr("type").equals("fill_choice")) { // 填空
            questionScore = test.getInt("rand_fill_score");
        }
        return questionScore;
    }

    /**
     * 保存更新分数
     *
     * @param testpaperItem
     * @param testpaper
     * @param testpaperResult
     * @param studentId
     * @param questionId
     * @param status
     * @param getScore
     * @param myAnswer
     */
    private void updateScore(TestpaperItem testpaperItem, Testpaper testpaper, TestpaperResult testpaperResult,
                             Long studentId, Long questionId, int status, int getScore, String myAnswer) {
        // 判断是否已存在已答题选项
        TestpaperItemResult answeredItemResult = TestpaperItemResult.dao.
                findByAnsweredQuestionId(Long.parseLong(testpaper.getBigInteger("id").toString()),
                        testpaperItem.getLong("id"), studentId, questionId);
        if (answeredItemResult == null) {
            TestpaperItemResult itemResult = getModel(TestpaperItemResult.class);
            // 保存选项答案
            TestpaperItemResult.dao.saveTestpaperItemResult(itemResult, testpaperItem.getLong("id"),
                    Long.parseLong(testpaper.getBigInteger("id").toString()),
                    Long.parseLong(testpaperResult.getBigInteger("id").toString()), studentId, questionId, status, getScore, myAnswer);
            if (status != 0) {
                testpaperResult.set("score", testpaperResult.getInt("score") + getScore);
            }
        } else {
            if (status == 0) {
                if (testpaperResult.getInt("score") > 0) {
                    if (testpaperResult.getInt("score") - getScore > 0) {
                        testpaperResult.set("score", testpaperResult.getInt("score") - getScore);
                    }
                }
            }
            //更新选项
            TestpaperItemResult.dao.updateItemResult(answeredItemResult, status, getScore, myAnswer);
        }
        testpaperResult.set("status", "draft");
        testpaperResult.update();
    }
}
